package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserAddressMapper;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserInfo login(String username, String password) {
        //参数校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码不能为空！");
        }
        //查询用户
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getLoginName, username));
        //判断用户是否存在
        if (userInfo == null || userInfo.getId() == null){
            throw new RuntimeException("用户名或密码错误");
        }
        //判断密码
        String passWordDb = userInfo.getPasswd();
        //将明文进行MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(passWordDb)){
            throw new RuntimeException("用户名或密码错误");
        }
        return userInfo;
    }

    /**
     * 根据用户id查询用户的收货地址
     *
     * @param userId
     * @return
     */
    @Override
    public List<UserAddress> getUserAddressList(Long userId) {
        return userAddressMapper.selectList(
                new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUserId,userId)
        );
    }
}
